package com.jcode.netty.server;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @Desc
 * @Author dreajay
 * @DateTime 2016年10月15日 上午11:15:40
 */
public class MultipleNettyServer extends NettyServer {

    private static final Logger logger = LoggerFactory.getLogger(MultipleNettyServer.class);

    public MultipleNettyServer(ServerConfig config) {
        super(config);
    }

    private List<Integer> excludeList = new ArrayList<Integer>();

    @Override
    protected void bindAddress() {
        for (final int port : config.getListenPortList()) {
            bootstrap.bind(config.getBindIp(), port).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    if (f.isSuccess()) {
                        logger.error("Started Server success with listen port: {}", port);
                    } else {
                        // 绑定监听端口，如果没有启动成功，尝试重启
                        logger.error("Started Server Failed, the port {} is already inuse {}", port, f.toString());
                        excludeList.add(port);
                        System.err.println("already inuse port:" + port);

//                        f.channel().eventLoop().schedule(new Runnable() {
//                            @Override
//                            public void run() {
//                                bindAddress();
//                            }
//                        }, 5, TimeUnit.SECONDS);
                    }
                }
            });
        }


    }

    public List<Integer> getExcludeList() {
        return excludeList;
    }

}
